package com.thinkcar.test.boot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thinkcar.core.exception.extension.CommonException;
import com.thinkcar.core.utils.RestTemplateUtil;
import com.thinkcar.redis.utils.RedisUtils;
import com.thinkcar.test.boot.entity.User;
import com.thinkcar.test.boot.enums.ExceptionEnum;
import com.thinkcar.test.boot.mapper.UserMapper;
import com.thinkcar.test.boot.reqparam.GetUsersPageReq;
import com.thinkcar.test.boot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author: jiangyong
 * @date: 2025/10/19
 * @description: UserServiceImpl
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    Random random = new Random();

    private static final String REDIS_KEY = "key111";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Override
    public Page<User> getUsersPage(GetUsersPageReq requestParam) {
        // 创建分页对象

        // 创建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, requestParam.getId());
        //RestTemplate请求
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        String response = restTemplateUtil.get(url, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        LOGGER.info("RestTemplate请求结果：{}", jsonObject);
        //存入redis
        RedisUtils.set(REDIS_KEY, response);
        String redisResponse = RedisUtils.get(REDIS_KEY);
        if (random.nextBoolean()) {
            LOGGER.error("redis中不存在该key,key=[{}]", REDIS_KEY);
            throw new CommonException(ExceptionEnum.REDIS_NOT_FOUND, REDIS_KEY);
        }
        LOGGER.info("redisResponse：{}", redisResponse);

        Page<User> page = new Page<>(requestParam.getPageNum(), requestParam.getPageSize());
        Page<User> userPage = this.page(page, queryWrapper);
//        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        return userPage;
    }
}
